import { Ref } from "vue";
import { BaseQuery } from "@/entity/BaseQuery";
import BaseOrder from "@/entity/BaseOrder";
import { useGlobalSettingStore, useUrlStore } from "@/store";
import MessageUtil from "@/utils/model/MessageUtil";
import { clientSearchBaseApi } from "@/api";
import { useSnowflake } from "$/util";

export type { Ref };

export interface BaseSearchInstanceResult {
  id: string;
  // 索引:类型
  index: Ref<string>;
  // 条件
  query: Ref<Array<BaseQuery>>;
  // 排序
  orders: Ref<Array<BaseOrder>>;
  // 页码
  pageNum: Ref<number>;
  // 每页大小
  pageSize: Ref<number>;
  // 总数
  total: Ref<number>;
  // 结果
  result: Ref<string>;

  run: () => void;
}

export const useBaseSearchInstance = (): BaseSearchInstanceResult => {
  const index = ref("");
  const query = ref(new Array<BaseQuery>());
  const orders = ref(new Array<BaseOrder>());
  const pageNum = ref(1);
  const pageSize = ref(useGlobalSettingStore().pageSize);

  const total = ref(0);
  const loading = ref(false);
  const result = ref("");

  const run = () => {
    const { id } = useUrlStore();
    if (!id) return MessageUtil.warning("请选择索引");
    if (loading.value) return;
    clientSearchBaseApi(id, {
      index: index.value,
      query: query.value,
      order: orders.value,
      pageNum: pageNum.value,
      pageSize: pageSize.value
    })
      .then((r) => {
        total.value = r.total;
        result.value = r.data;
      })
      .finally(() => {
        loading.value = false;
      });
  };

  return {
    id: useSnowflake().nextId(),
    index,
    query,
    orders,
    pageNum,
    pageSize,
    total,
    result,
    run
  };
};
